package com.zlk.algorithm.dataStructure.preSum;

import org.junit.Test;

/**
 * @program: algorithm
 * @ClassName Index
 * @description:前准和
 * @author: slfang
 * @create: 2023-12-11 18:24
 * @Version 1.0
 **/
public class Index {


    /**
     * 获取数组  从 L位置到R位置的和
     */
    public int getL2RArrSum(int l,int r,int[] arr) throws Exception {
        if(l>r){
            throw new Exception("l不能大于r");
        }
        if(l==r){
            return 0;
        }
        int len = arr.length;
        int[] help = new int[len];
        //构建前缀数数组
        help[0] = arr[0];
        for (int i = 1; i < len; i++) {
            help[i] = arr[i]+help[i-1];
        }
        //9,1,2,4,5,6,3,2,1,0,8
        //9 10 12 16 21 27 30 32 33 33 41
        return l==0?help[r]:help[r]-help[l-1];
    }


    @Test
    public void test1() throws Exception {
        int[] arr = new int[]{9,1,2,4,5,6,3,2,1,0,8};
        System.out.println(getL2RArrSum(0, 6, arr));
        System.out.println(getL2RArrSum(1, 6, arr));
        System.out.println(getL2RArrSum(3, 6, arr));
        System.out.println(getL2RArrSum(2, 5, arr));
        System.out.println(getL2RArrSum(1, 3, arr));
    }


}
